package com.yh.ldzl.controller;

import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.api.BasicService;
import com.ruoyi.system.api.InventoryService;
import com.yh.ldzl.domain.QcIqc;
import com.yh.ldzl.domain.QcIqcLine;
import com.yh.ldzl.domain.QcTemplate;
import com.yh.ldzl.domain.QcTemplateProduct;
import com.yh.ldzl.service.IQcIqcLineService;
import com.yh.ldzl.service.IQcIqcService;
import com.yh.ldzl.service.QcTemplateProductService;
import com.yh.ldzl.service.QcTemplateService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;


/**
 * 来料检测单控制器
 */
@RestController
@RequestMapping("qc/iqc")
public class QcIqcController extends BaseController
{
    @Autowired
    private IQcIqcService qcIqcService;

    @Autowired
    private QcTemplateService qcTemplateService;

    @Autowired
    private QcTemplateProductService qcTemplateProductService;

    @Autowired
    private IQcIqcLineService qcIqcLineService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private InventoryService inventoryService;

    // 消息类型常量，应与RecordActionController中的常量保持一致
    private static final String MESSAGE_TYPE_HEADER = "message_type";
    private static final String MESSAGE_TYPE_QC_IQC = "qc_iqc";

    /**
     * 查询ldzl-qc列表
     */
    @GetMapping("/selectQcIqcList")
    public TableDataInfo list(QcIqc qcIqc)
    {

        startPage();
        List<QcIqc> list = qcIqcService.selectQcIqcList(qcIqc);
        return getDataTable(list);
    }

    /**
     * 导出ldzl-qc列表
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QcIqc qcIqc)
    {
        List<QcIqc> list = qcIqcService.selectQcIqcList(qcIqc);
        ExcelUtil<QcIqc> util = new ExcelUtil<QcIqc>(QcIqc.class);
        util.exportExcel(response, list, "ldzl-qc数据");
    }

    /**
     * 获取ldzl-qc详细信息
     */
    @GetMapping("selectQcIqcDetailed/{iqcId}")
    public AjaxResult getInfo(@PathVariable("iqcId") Long iqcId)
    {
        return success(qcIqcService.selectQcIqcByIqcId(iqcId));
    }

    /**
     * 新增ldzl-qc
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.INSERT)
    @PostMapping("insertQcIqc")
    public AjaxResult add(QcIqc qcIqc)
    {
        try {
            int result = qcIqcService.insertQcIqc(qcIqc);
            if (result <= 0) {
                return AjaxResult.error("新增QC检测单失败");
            }
            
            Long iqcId = qcIqc.getIqcId();
            System.out.println("iqcId:" + iqcId + ", 准备发送消息");

            // 创建消息关联ID，便于跟踪消息
            String correlationId = "qc-iqc-" + iqcId + "-" + System.currentTimeMillis();
            CorrelationData correlationData = new CorrelationData(correlationId);
            
            // 创建消息头部，设置消息类型
            org.springframework.amqp.core.MessagePostProcessor messagePostProcessor = message -> {
                MessageProperties properties = message.getMessageProperties();
                properties.setHeader(MESSAGE_TYPE_HEADER, MESSAGE_TYPE_QC_IQC);
                return message;
            };
            
            // 发送消息，并使用correlationData跟踪，附加消息类型
            rabbitTemplate.convertAndSend(
                "myExchange", 
                "myRoutingKey", 
                qcIqc, 
                messagePostProcessor,
                correlationData
            );
            
            System.out.println("iqcId:" + iqcId + ", 消息已发送, correlationId: " + correlationId + ", messageType: " + MESSAGE_TYPE_QC_IQC);
            
            return AjaxResult.success("新增QC检测单成功，消息已发送");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送消息异常: " + e.getMessage());
            return AjaxResult.error("操作异常: " + e.getMessage());
        }
    }

    /**
     * 修改ldzl-qc
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.UPDATE)
    @PostMapping("updateQcIqc")
    public AjaxResult edit(@RequestBody QcIqc qcIqc)
    {
        return toAjax(qcIqcService.updateQcIqc(qcIqc));
    }

    /**
     * 删除ldzl-qc
     */

    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
	@PostMapping("deleteQcIqc/{iqcIds}")
    public AjaxResult remove(@PathVariable Long[] iqcIds)
    {
        return toAjax(qcIqcService.deleteQcIqcByIqcIds(iqcIds));
    }

    /**
     * 查询模板列表
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
	@PostMapping("selectQcTemplateBasicInformation")
    public TableDataInfo selectQcTemplateById() {
        List<QcTemplate> list = qcTemplateService.selectQcTemplateBasicInformation();

        return getDataTable(list);
    }
    /**
     * 查询模板下的要检测物料列表
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
    @PostMapping("selectQcTemplateProductItemInformationTemplateId")
    public TableDataInfo selectQcTemplateProductItemInformationTemplateId(QcTemplateProduct qcTemplateProduct) {
        List<QcTemplateProduct> list = qcTemplateProductService.selectQcTemplateProductItemInformationTemplateId(qcTemplateProduct);
                return getDataTable(list);
    }

    /**
     * 防止生成重复物料的检测单，根据来源单据ID和物料编码判断是否重复，返回true表示不重复，返回false表示重复
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
    @PostMapping("selectQcIqcCodeUnique")
    public boolean selectQcIqcCodeUnique(@RequestParam int source_doc_id,@RequestParam String material_code) {

        return qcIqcService.selectQcIqcCodeUnique(source_doc_id,material_code);
    }

    /**
     * 查询检测单的检查项信息
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
    @PostMapping("selectQcIqcLineByLineId")
    public TableDataInfo selectQcIqcLineByLineId(QcIqcLine qcIqcLine) {
        startPage();
        List<QcIqcLine> list =qcIqcLineService.selectQcIqcLineList(qcIqcLine);
        return getDataTable(list);
    }
    /**
     * 添加检查项信息
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
    @PostMapping("insertQcIqcLine")
    public boolean insertQcIqcLine(QcIqcLine qcIqcLine) {
        return qcIqcLineService.insertQcIqcLine(qcIqcLine);
    }
    /**
     * 修改检查项信息
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
    @PostMapping("updateQcIqcLine")
    public boolean updateQcIqcLine(QcIqcLine qcIqcLine) {

        return qcIqcLineService.updateQcIqcLine(qcIqcLine);
    }
    /**
     * 删除批量检查项信息
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
    @PostMapping("deleteQcIqcLineByLineIds")
    public boolean deleteQcIqcLineByLineIds(Long[] lineIds) {
        return qcIqcLineService.deleteQcIqcLineByLineIds(lineIds);

    }
    /**
     * 删除检查项信息
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
    @PostMapping("deleteQcIqcLineByLineId")
    public boolean deleteQcIqcLineByLineId(Long lineId) {
        return qcIqcLineService.deleteQcIqcLineByLineId(lineId);

    }
    /**
     * 检测单检查项编码重复性验证
     */
    @Log(title = "ldzl-qc", businessType = BusinessType.DELETE)
    @PostMapping("selectQcIqcLineCodeUnique")
    public boolean selectQcIqcLineCodeUnique(String iqc_code) {

        return qcIqcService.selectQcIqcLineCodeUnique(iqc_code);
    }
    /**
     * 查询检测单的详细信息
     */
    @PostMapping("selectQcIqcDetailed")
    public QcIqc selectQcIqcDetailed(@RequestParam String iqc_code) {
        QcIqc qcIqc = qcIqcService.selectQcIqcDetail(iqc_code);
        System.out.println("qcIqc:"+qcIqc);
        return qcIqc;
    }


    /**
     * 兼容InventoryService接口的待检测入库单查询
     * 使用GET请求和路径变量格式，匹配实际实现（ReceiptController）
     */
    @GetMapping("/receipt/selectCkProductRecptDetectSingle/{recpt_code}/{recpt_name}/{status}")
    public TableDataInfo selectCkProductRecptDetectSingleCompat(@PathVariable(value = "recpt_code", required = false) String recpt_code,@PathVariable(value = "recpt_name", required = false) String recpt_name,@PathVariable("status") String  status) {

        return inventoryService.selectCkProductRecptDetectSingle(recpt_code,recpt_name, status);
    }

    /**
     * 为兼容前端GET请求+参数方式，增加一个转发方法
     */
    @GetMapping("/receipt/selectCkProductRecptDetectSingle")
    public TableDataInfo selectCkProductRecptDetectSingleGet(@RequestParam(value = "recpt_code", required = false) String recpt_code,@RequestParam(value = "recpt_name", required = false) String recpt_name,@RequestParam("status") String  status) {
        // 处理可能的null值，Feign不允许路径变量为null或空字符串
        // 使用占位符"%"代替空值，确保URL路径正确（避免使用"_"作为通配符）
        String code = (recpt_code == null || recpt_code.isEmpty()) ? "%" : recpt_code;
        String name = (recpt_name == null || recpt_name.isEmpty()) ? "%" : recpt_name;
        return selectCkProductRecptDetectSingleCompat(code, name,status);
    }

    /**
     * 查询指定采购入库单下的商品
     * @param recpt_id
     * @return
     */
    @PostMapping("receipt/findReceipt_id/{recpt_id}")
    public TableDataInfo findReceipt_id(@PathVariable("recpt_id") Long recpt_id){
        return inventoryService.findReceipt_id_qc(recpt_id);
    }





}
